package com.ruoyi.framework.web.service;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.config.WxMaConfig;
import com.ruoyi.system.domain.WxLoginBody;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.hibernate.validator.constraints.EAN;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class WxLoginService {
    @Autowired
    private WxMaConfig wxMaConfig;

    @Autowired
    private ISysUserService userService;

    @Resource
    private TokenService tokenService;
    @Resource
    SysPermissionService permissionService;
    @Resource
    ISysConfigService configService;

    @Transactional
    public AjaxResult wxLogin(WxLoginBody wxLoginBody) {
        // 1. 通过code获取openid和session_key
        String url = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                wxMaConfig.getAppid(), wxMaConfig.getSecret(), wxLoginBody.getCode());
        String result = HttpUtil.get(url);
        JSONObject json = JSONObject.parseObject(result);

        if (json.containsKey("errcode") && json.getIntValue("errcode") != 0) {
            return AjaxResult.error("微信登录失败：" + json.getString("errmsg"));
        }

        String openid = json.getString("openid");
        if (StringUtils.isEmpty(openid)) {
            return AjaxResult.error("获取微信openid失败");
        }

        // 2. 查找或创建用户
        SysUser user = userService.selectUserByOpenid(openid);
        if (user == null) {
            // 创建新用户
            user = new SysUser();
            user.setOpenid(openid);
            user.setNickName("test");
            // 设置其他必要的用户信息
            user.setUserName("wx_" + openid.substring(0, 8));
            //参数设置中的默认密码
            String password = configService.selectConfigByKey("sys.user.initPassword");
            user.setPassword(SecurityUtils.encryptPassword(password));
            user.setDeptId(100L); // 设置默认部门
            user.setStatus("0"); // 正常状态
            userService.insertUser(user);
        }

        // 3. 生成token
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(user.getUserId());
        loginUser.setUser(user);
        // 获取用户权限
        loginUser.setPermissions(permissionService.getMenuPermission(user));
        String token = tokenService.createToken(loginUser);

        AjaxResult ajax = AjaxResult.success();
        ajax.put("token", token);
        return ajax;

    }
}
